package com.cp.dao.extendLanguageDriver;

import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 避免在注解中select in 语句使用 foreach循环
 * 需要在对应的方法前添加注解@Lang(SelectInExtendLanguageDriver.class)，此注解只用于Mapper
 */
public class SelectInExtendLanguageDriver extends XMLLanguageDriver implements LanguageDriver {
	private final Pattern inPattern = Pattern.compile("\\([\\d]*#[\\d]*\\{[\\d]*(\\w+)[\\d]*\\}[\\d]*\\)");
	@Override
	public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
		Matcher matcher = inPattern.matcher(script);
		if (matcher.find()) {
			script = matcher.replaceAll("(<foreach collection=\"$1\" item=\"__item\" separator=\",\" >#{__item}</foreach>)");
		}

		script = "<script>" + script + "</script>";
		return super.createSqlSource(configuration, script, parameterType);
	}
}
